
package com.qf.BaseController;

import com.qf.utils.Constants;
import com.sun.deploy.net.HttpResponse;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;



public class BaseServlet extends HttpServlet {

    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        String methodStr = req.getParameter(Constants.TAG);
        if(methodStr==null||"".equals(methodStr)){
          methodStr=Constants.INDEX;

        }
        //3. 反射调用对应的业务逻辑方法
        //获取class类
        Class clazz = this.getClass();

        try {
            //4. 从类中获取方法对象
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
            //5. 执行从类中获取到的方法对象, 接收方法执行结果
            Object invoke = method.invoke(this, req, res);
            //6. 根据返回的结果进行判断, 判断返回值不为空
            if(invoke!=null){
                //jump获取到后例如: "forward:http://localhost:8080/admin/admin.jsp"
            String jump= (String) invoke;

            if(jump.startsWith(Constants.FORWARD)){
                //7. 判断执行后是请求转发处理
                //获取路径, 例如: http://localhost:8080/admin/admin.jsp
                String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                //执行请求转发
                req.getRequestDispatcher(path).forward(req, res);
            }else  if(jump.startsWith(Constants.REDIRECT)){
                //8. 判断执行后是重定向处理
                //获取路径, 例如: http://localhost:8080/admin/admin.jsp
                String path= jump.substring(jump.indexOf(Constants.FLAG) + 1);
                res.sendRedirect(path);
            }
            else{
                //9. 判断如果是其他类型的返回值, 那么通过流写回到浏览器页面
                res.getWriter().println(jump);

            }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

